package com.ovopark.organize.server.util;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ovopark.device.common.util.LogUtil;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class HttpUtils {
    private static Logger log = LoggerFactory.getLogger(HttpUtils.class);
    public static String doPost(String url, Object params,Integer timeOut) throws Exception {
        if (timeOut == null){
            timeOut = 10000;
        }
        RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setConfig(requestConfig);
        httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(JSON.toJSONString(params), charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;

        try {

            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                return EntityUtils.toString(responseEntity, charSet);


            } else {
                log.error("请求返回:" + state + "(" + url + ")");
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String doPostWithExtraHeaders(String url, Map<String, String> extraHeaders, Map<String, Object> params, Integer timeOut) throws Exception {
        if (timeOut == null){
            timeOut = 10000;
        }
        RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();

        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);// 创建httpPost
        httpPost.setConfig(requestConfig);
     //   httpPost.setHeader("Accept", "application/json");
        httpPost.setHeader("Content-Type", "application/json");

        if (extraHeaders != null) {
            Iterator<Map.Entry<String, String>> entries = extraHeaders.entrySet().iterator();
            while(entries.hasNext()){
                Map.Entry<String, String> entry = entries.next();
                httpPost.setHeader(entry.getKey(), entry.getValue());
            }
        }
        String charSet = "UTF-8";
        StringEntity entity = new StringEntity(JSON.toJSONString(params), charSet);
        httpPost.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpPost);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String result = EntityUtils.toString(responseEntity, charSet);
                log.info("request url:" + url + "; response:" + result);
                return result;
            } else {
                log.error("请求返回:" + state + "(" + url + ")");
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String doGetWithExtraHeaders(String url, Map<String, String> extraHeaders, Map<String, Object> params, Integer timeOut) throws Exception {
        if (timeOut == null){
            timeOut = 10000;
        }
        RequestConfig requestConfig =  RequestConfig.custom().setSocketTimeout(timeOut).setConnectTimeout(timeOut).build();

        CloseableHttpClient httpclient = HttpClients.createDefault();
        if (params != null) {
            Iterator<Map.Entry<String, Object>> entries = params.entrySet().iterator();
            // 第一个用?连接，后续的用&
            String connectionStr = "?";
            while(entries.hasNext()){
                Map.Entry<String, Object> entry = entries.next();
                // URL Encode
                url += connectionStr + entry.getKey() + "=" + entry.getValue();
                connectionStr = "&";
            }
        }
        HttpGet httpGet = new HttpGet(url);// 创建httpPost
        httpGet.setConfig(requestConfig);
//        httpPost.setHeader("Accept", "application/json");
//        httpGet.setHeader("Content-Type", "application/json");
        if (extraHeaders != null) {
            Iterator<Map.Entry<String, String>> entries = extraHeaders.entrySet().iterator();
            while(entries.hasNext()){
                Map.Entry<String, String> entry = entries.next();
                httpGet.setHeader(entry.getKey(), entry.getValue());
            }
        }
        String charSet = "UTF-8";
//        StringEntity entity = new StringEntity(JSON.toJSONString(params), charSet);
//        httpGet.setEntity(entity);
        CloseableHttpResponse response = null;
        try {
            response = httpclient.execute(httpGet);
            StatusLine status = response.getStatusLine();
            int state = status.getStatusCode();
            if (state == HttpStatus.SC_OK) {
                HttpEntity responseEntity = response.getEntity();
                String result = EntityUtils.toString(responseEntity, charSet);
                log.info("request url:" + url + "; response:" + result);
                return result;
            } else {
                log.error("请求返回:" + state + "(" + url + ")");
            }
        } finally {
            if (response != null) {
                try {
                    response.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            try {
                httpclient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return null;
    }

    public static String sendGetToOtherServer(String url) {
        String result = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpGet httpGet = new HttpGet(url);
        try {
            httpGet.setHeader("Content-type","application/json; charset=utf-8");

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(30000).setConnectionRequestTimeout(30000)
                    .setSocketTimeout(30000).build();
            httpGet.setConfig(requestConfig);

            CloseableHttpResponse response = httpclient.execute(httpGet);

            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == 200){
                HttpEntity httpEntity = response.getEntity();
                result = EntityUtils.toString(httpEntity, "utf-8");
                //			log.info("result = " + result);
            }else {
                log.error("send url = "+ url + " recv statusCode = " + statusCode);
            }
        } catch (Exception e) {
            log.error("sendGetToOtherServer", e);
        } finally {
            httpGet.releaseConnection();
        }

        return result;
    }

    public static String sendPostToOtherServer(String url, Map<String, Object> params) {
        String result = "";

        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            List<NameValuePair> pairList = new ArrayList(params.size());
            Iterator var6 = params.entrySet().iterator();

            while(var6.hasNext()) {
                Map.Entry<String, Object> entry = (Map.Entry)var6.next();
                NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());
                pairList.add(pair);
            }

            httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
            httpPost.setConfig(requestConfig);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                HttpEntity httpEntity = response.getEntity();
                result = EntityUtils.toString(httpEntity);
                log.info("result = " + result);
            } else {
                log.error("send url = " + url + " recv statusCode = " + statusCode);
            }
        } catch (Exception var10) {
            log.error("sendPostToOtherServer", var10);
        }

        return result;
    }
    public static String sendPostToTokenServer(String url, Map<String, Object> params,String token)throws Exception {
        String result = "";
        try {
            CloseableHttpClient httpclient = HttpClients.createDefault();
            HttpPost httpPost = new HttpPost(url);
            httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpPost.setHeader("Ovo-Authorization", token);
            List<NameValuePair> pairList = new ArrayList(params.size());
            Iterator var6 = params.entrySet().iterator();

            while(var6.hasNext()) {
                Map.Entry<String, Object> entry = (Map.Entry)var6.next();
                NameValuePair pair = new BasicNameValuePair((String)entry.getKey(), entry.getValue().toString());
                pairList.add(pair);
            }

            httpPost.setEntity(new UrlEncodedFormEntity(pairList, Charset.forName("UTF-8")));
            RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(30000).setConnectionRequestTimeout(30000).setSocketTimeout(30000).build();
            httpPost.setConfig(requestConfig);
            CloseableHttpResponse response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if (statusCode == 200) {
                HttpEntity httpEntity = response.getEntity();
                result = EntityUtils.toString(httpEntity);
                log.info("result = " + result);
            } else {
                log.error("send url = " + url + " recv statusCode = " + statusCode);
            }
        } catch (Exception var10) {
            log.error("sendPostToOtherServer", var10);
        }

        return result;
    }
    public static String sendJsonAndTokenToOtherServer(String url, Object data,String token) {
        String result = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.addHeader("Content-type","application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setHeader("Ovo-Authorization", token);
            httpPost.setEntity(new StringEntity(JSONObject.toJSONString(data), Charset.forName("UTF-8")));

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(30000).setConnectionRequestTimeout(30000)
                    .setSocketTimeout(30000).build();
            httpPost.setConfig(requestConfig);

            CloseableHttpResponse response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == 200){
                HttpEntity httpEntity = response.getEntity();
                result = EntityUtils.toString(httpEntity);
                log.info("result = " + result);
            }else {
                log.error("send url = "+ url + " recv statusCode = " + statusCode);
            }
        } catch (Exception e) {
            log.error("sendJsonToOtherServer", e);
        } finally {
            httpPost.releaseConnection();
        }

        return result;
    }
    public static String sendJsonToOtherServer(String url, Object data) {
        String result = "";
        CloseableHttpClient httpclient = HttpClients.createDefault();
        HttpPost httpPost = new HttpPost(url);
        try {
            httpPost.addHeader("Content-type","application/json; charset=utf-8");
            httpPost.setHeader("Accept", "application/json");
            httpPost.setEntity(new StringEntity(JSONObject.toJSONString(data), Charset.forName("UTF-8")));

            RequestConfig requestConfig = RequestConfig.custom()
                    .setConnectTimeout(30000).setConnectionRequestTimeout(30000)
                    .setSocketTimeout(30000).build();
            httpPost.setConfig(requestConfig);

            CloseableHttpResponse response = httpclient.execute(httpPost);
            int statusCode = response.getStatusLine().getStatusCode();
            if(statusCode == 200){
                HttpEntity httpEntity = response.getEntity();
                result = EntityUtils.toString(httpEntity);
                log.info("result = " + result);
            }else {
                log.error("send url = "+ url + " recv statusCode = " + statusCode);
            }
        } catch (Exception e) {
            log.error("sendJsonToOtherServer", e);
        } finally {
            httpPost.releaseConnection();
        }

        return result;
    }

    public static String sendJsonToOtherServerDefault(String url, Map<String,String> map) {

        // 创建httpClient对象
        HttpClient client = new HttpClient();
        PostMethod post = new PostMethod(url);

        if(map != null && map.size() > 0) {

            org.apache.commons.httpclient.NameValuePair[] nameValuePair = new org.apache.commons.httpclient.NameValuePair[map.size()];
            int i = 0;
            for (String key : map.keySet()) {
                org.apache.commons.httpclient.NameValuePair nameValuePairTmp = new org.apache.commons.httpclient.NameValuePair();
                nameValuePair[i] = nameValuePairTmp;
                nameValuePair[i].setName(key);
                nameValuePair[i].setValue(map.get(key));
                i++;
            }

            post.setRequestBody(nameValuePair);
        }

        post.getParams().setParameter(
                HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        HttpConnectionManagerParams managerParams = client
                .getHttpConnectionManager().getParams();
        // 设置连接超时时间(单位毫秒)
        managerParams.setConnectionTimeout(60000);
        // 设置读数据超时时间(单位毫秒)
        managerParams.setSoTimeout(60000);

        try {
            // 发送数据
            int code=client.executeMethod(post);
            if (code==200) {
                return post.getResponseBodyAsString();
            }
        } catch (Exception e) {
            log.error(LogUtil.getStackTraceInfo(e));
        }finally {
            // 关闭连接
            post.releaseConnection();
        }

        return null;

    }
}
